package project.vip.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

import net.sf.json.JSONObject;
import project.order.work.AccessTokenThread;

public class VipWxOpenIdHelper {
	public static JSONObject getJsonObGet(String openId) {
		String access_user_baseinformation = API4GZH.ACCESS_USER_BASEINFORMATION;
		String requestUrl = access_user_baseinformation.replace("ACCESS_TOKEN",
				AccessTokenThread.access_token).replace("OPENID", openId);
		System.out.println("获取用户信息url:"+requestUrl);
		JSONObject json = null;// 初值
		// send to 微信
		try {
			URL url = new URL(requestUrl);

			trustAllHttpsCertificates();
			HttpsURLConnection.setDefaultHostnameVerifier(hv);

			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setDoOutput(false);
			// 获取InputStream的值
			InputStream is = null;
			
			try {
				is = conn.getInputStream();
				String sReturn = new String(readInputStream(is), ("UTF-8"));
				System.out.println("WxOpenIdHelper get winxin Message:"
						+ sReturn);
				is.close();
				// 获得json对象，catch中的异常也需要使用这个值
				json = JSONObject.fromObject(sReturn);
				

			} catch (Exception ex) {
				if (json != null) {
					System.out.println((Integer) json.get("errcode"));
					System.out.println((String) json.get("errmsg"));
					System.out.println("json:" + json.toString());
				}
				ex.printStackTrace();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return json;

	}
	
	// 以下开始时https的信任默认代码
	static HostnameVerifier hv = new HostnameVerifier() {
		public boolean verify(String urlHostName, SSLSession session) {
			System.out.println("Warning: URL Host: " + urlHostName + " vs. "
					+ session.getPeerHost());
			return true;
		}
	};

	public static void main(String[] args) {
		String redirect_uri = "http://www.mrshine.cn/root/public/orderAction!view.action";
		try {
			System.out.println(URLEncoder.encode(redirect_uri, "utf-8"));
			System.out.println(URLEncoder.encode(redirect_uri, "gbk"));
			System.out.println(URLEncoder.encode(redirect_uri, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String getCodeUrl(String state, String wxuri) {

		String url = "";
		try {
			url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
					+ AccessTokenThread.appid + "&redirect_uri="
					+ URLEncoder.encode(wxuri, "utf-8")
					+ "&response_type=code&scope=snsapi_base&state=" + state
					+ "#wechat_redirect";
			System.out.println("wx跳转url:" + url);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// String url =
		// "http://127.0.0.1:8099/root/public/orderAction!view.action?state="+state;
		return url;
	}

	public static String getOpenId(String code) {

		String openid = null;

		// send to 微信
		try {
			URL url = new URL(
					"https://api.weixin.qq.com/sns/oauth2/access_token?appid="
							+ AccessTokenThread.appid + "&secret="
							+ AccessTokenThread.secret + "&code=" + code
							+ "&grant_type=authorization_code");

			trustAllHttpsCertificates();
			HttpsURLConnection.setDefaultHostnameVerifier(hv);

			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setDoOutput(false);
			// 获取InputStream的值
			InputStream is = null;
			JSONObject json = null;// 初值
			try {
				is = conn.getInputStream();
				String sReturn = new String(readInputStream(is), ("UTF-8"));
				System.out.println("WxOpenIdHelper get winxin Message:"
						+ sReturn);
				is.close();
				// 获得json对象，catch中的异常也需要使用这个值
				json = JSONObject.fromObject(sReturn);
				// 设置静态变量
				openid = (String) json.get("openid");
				// System.out.println("openid:"+openid);

			} catch (Exception ex) {
				if (json != null) {
					System.out.println((Integer) json.get("errcode"));
					System.out.println((String) json.get("errmsg"));
					System.out.println("json:" + json.toString());
				}
				ex.printStackTrace();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return openid;

	}

	private static void trustAllHttpsCertificates() throws Exception {
		javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
		javax.net.ssl.TrustManager tm = new Mitm();
		trustAllCerts[0] = tm;
		javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
				.getInstance("SSL");
		sc.init(null, trustAllCerts, null);
		javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
				.getSocketFactory());
	}

	static class Mitm implements javax.net.ssl.TrustManager,
			javax.net.ssl.X509TrustManager {
		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			return null;
		}

		public boolean isServerTrusted(
				java.security.cert.X509Certificate[] certs) {
			return true;
		}

		public boolean isClientTrusted(
				java.security.cert.X509Certificate[] certs) {
			return true;
		}

		public void checkServerTrusted(
				java.security.cert.X509Certificate[] certs, String authType)
				throws java.security.cert.CertificateException {
			return;
		}

		public void checkClientTrusted(
				java.security.cert.X509Certificate[] certs, String authType)
				throws java.security.cert.CertificateException {
			return;
		}
	}

	public static byte[] readInputStream(InputStream inStream) {
		byte[] data = null;
		try {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			data = outStream.toByteArray();//
			outStream.close();
			inStream.close();

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return data;
	}
}
